﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

public class Stock
{
    public enum StockID
    {
        TEN_XUN=100,
        REN_DI_YU,
        LUAN_SHU,
        SUO_NI,
        WEI_RUAN,
        LAI_YANG,
        DA_MI,
        NI_FENG
    }
    public string m_Name;
    public string m_Describe;
    public float m_BasePrice;
    public StockID m_ID;
    int m_BaseDay = 727740;
    int m_ThedayDetailNumber = 0;
    public float m_ThedayPrice = 0;
    public float m_YesterdayPrice = 0;
    public float m_TomorrowPrice = 0;
    public int m_Now=0;
    protected BerlinNoise m_BaseRandomer = new BerlinNoise();
    public Stock()
    {
        m_ThedayDetailNumber = GetThedayDetailNumber(UtilsGame.GetSeedToday());
    }

    public void Init()
    {
        m_ThedayPrice = CalcPrice();
        m_YesterdayPrice = CalcPriceAtOneday(UtilsGame.GetSeedToday() - 1);
        m_TomorrowPrice = CalcPriceAtOneday(UtilsGame.GetSeedToday() + 1);
    }
    public float CalcPrice()
    {
        int today = UtilsGame.GetSeedToday();
        return CalcPriceAtOneday(today);
    }
    public float CalcPriceAtOneday(int daySeed)
    {
        float newPrice = m_BasePrice;
        for (int i = m_BaseDay; i <= daySeed; ++i)
        {
            float theDayRate = GetRandom(i) * 0.1f;
            newPrice += newPrice * theDayRate;
        }
        return newPrice;
    }

    public float GetRateAtOneday(int daySeed)
    {
        return GetRandom(daySeed) * 10f;
    }
    public float GetRateToDay()
    {
        return GetRateAtOneday(UtilsGame.GetSeedToday());
    }

    public float GetRandom(int index)
    {
        m_BaseRandomer.setSeed((int)m_ID);
        return m_BaseRandomer.berlinNoise(index);
    }

    public int GetThedayDetailNumber(int daySeed)
    {
        int number = (int)(((UtilsMath.rand(daySeed, daySeed) + 1) * 0.5f) * 50) + 50;
        return number;
    }

    public float GetPriceNow ()
    {
        int now = UtilsGame.GetSeedNow();
        if (now < m_Now)
            Init();
        m_Now = now;
        float oneStepSecond = ((24*60*60) /  (float)m_ThedayDetailNumber);

        int nowStep = (int)(m_Now / oneStepSecond);
        float nowStepProcess = (m_Now % oneStepSecond) / (float)oneStepSecond;

        float nowPrice = m_ThedayPrice;
        for (int i=0; i<= nowStep; ++i)
        {
            nowPrice += nowPrice * (GetRandom(UtilsGame.GetSeedToday() + i) * 0.05f);
            //  如果超过10%则涨停或跌停
            nowPrice = Mathf.Clamp(nowPrice, m_ThedayPrice - m_ThedayPrice*0.1f, m_ThedayPrice + m_ThedayPrice * 0.1f);
        }
        float nowPriceP = nowPrice;
        if (nowStep == m_ThedayDetailNumber-1)
            nowPrice = Mathf.Lerp(nowPriceP, m_TomorrowPrice, nowStepProcess);
        else
            nowPrice += nowPriceP * (GetRandom(UtilsGame.GetSeedToday() + nowStep + 1) * 0.1f * nowStepProcess);
        return nowPrice;
    }
}